package it.aekidna.cleverplatypus.workflow.template
{
	import flash.events.Event;
	
	import it.aekidna.cleverplatypus.gui.containers.ContextualPopUpPanel;
	import it.aekidna.cleverplatypus.gui.containers.commonpopup.MultibuttonAnswerPopUpDialog;
	import it.aekidna.cleverplatypus.gui.containers.commonpopup.PopupDialogFactory;
	import it.aekidna.cleverplatypus.mediator.CommandEvent;
	import it.aekidna.cleverplatypus.workflow.AbstractWorkflowTask;
	
	import mx.rpc.events.ResultEvent;

	public class AskUserTask extends AbstractWorkflowTask
	{
		public var prompt : String = "REPLACE_ME";
		public var buttonLabels:Array; //of strings
		public var dialog : MultibuttonAnswerPopUpDialog;
		public var hotSpotName : String;
		
		[Bindable]
		public var model : Object;
		
		public function AskUserTask()
		{
			super();
		}
		
		override public function begin() : void
		{
			dialog = PopupDialogFactory.gimme(MultibuttonAnswerPopUpDialog) as MultibuttonAnswerPopUpDialog;
			if(dialog) {
				dialog.prompt = prompt;
				dialog.buttonLabels = buttonLabels;
				dialog.closeOnClick = false;
				dialog.addEventListener( ResultEvent.RESULT, onResult );
				dialog.addEventListener( Event.CANCEL, onFail );
				dialog.addEventListener(Event.REMOVED_FROM_STAGE, onPopupClosed);
				dialog.hotSpotName = hotSpotName;
				CommandEvent.createWithNamedParams( "SHOW_CONTEXTUAL_POP_UP_PANEL", { panel : dialog } ).dispatch();
			}
		}
		
		private function onResult( inEvent : ResultEvent ) : void
		{
			if(inEvent && inEvent.result)
				model.result = inEvent.result;
		}
		
		private function onPopupClosed(event:Event):void
		{
			this.recyclePopup(event.currentTarget as ContextualPopUpPanel);
			complete();
		}
		
		private function onFail( inEvent : Event ) : void
		{
			this.recyclePopup(inEvent.currentTarget as ContextualPopUpPanel);
			fail( "User aborted operation" );
		}
		
		
		private function recyclePopup(popup:ContextualPopUpPanel):void
		{
			popup.removeEventListener( ResultEvent.RESULT, onResult );
			popup.removeEventListener( Event.CANCEL, onFail );
			popup.removeEventListener(Event.REMOVED_FROM_STAGE, onPopupClosed);
			PopupDialogFactory.recycle(popup);
		}
	}
}